package com.sodaopen.crm.sys.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.sodaopen.crm.common.entity.AjaxResult;
import com.sodaopen.crm.sys.entity.User;
import com.sodaopen.crm.sys.service.IUserService;
import com.sodaopen.crm.utils.JwtUtil;

@RestController
public class LoginController {
	
	@Autowired
	private IUserService userService;

    @PostMapping("/login")
    public Object login(@RequestBody Map<String, String> loginUser){
    	User user = userService.findByUsername(loginUser.get("username"));
    	
    	if(user == null) {
    		return AjaxResult.BAD_REQUEST("用户不存在");
    	}else if(!user.isAvailable()) {
    		return AjaxResult.BAD_REQUEST("用户不可用");
    	}else if(!user.getPassword().equals(loginUser.get("password"))) {
    		return AjaxResult.BAD_REQUEST("密码错误");
    	}else {
    		Map<String, Object> data = new HashMap<>();
    		data.put("name", user.getName());
    		data.put("email", user.getEmail());
    		data.put("mobile", user.getMobile());
            
    		//创建token
            String token = JwtUtil.createJwt(user.getId().toString(), user.getUsername(), data); 
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            //通常做法，token前加上“Bearer ”，注意有空格
            data.put("token", "Bearer " + token); 
            
    		return AjaxResult.OK("登录成功！", data);
    	}
    }
}
